import { NetPacket } from "@/netBase/NetPacket";
import PKwebsocket from "@/lolo/Ws";
import { IGameRank } from "../types";
import { computed, ref } from "vue";
import { Page } from "@/store/page";
import pinia from "@/store";
import { storeToRefs } from "pinia";
import router from "@/router";
import { Local } from "@/utils/storage";

export function formatNumber(num: string | number) {
  if (!num) return ''
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

export function maskUsername(username: string) {
  if (!username) return ''
  return username.replace(/^(.{3}).*(.)$/, '$1***$2');
}


export function useRecentWin() {
  const { homeGameData } = storeToRefs(Page(pinia));

  const getMap = (item: any) => {
    if (!item.three_game) return
    let obj: any = {}
    homeGameData.value.forEach((plat: any) => {
      if (plat.three_platform) {
        plat.three_platform.forEach((kind: any) => {
          if (kind.id == item.three_game.agent_id) {
            if (kind.three_game_kind) {
              kind.three_game_kind.forEach((games: any) => {
                const target: any = games.three_game.find((game: any) => game.gameId == item.three_game.game_id)
                if (target) {
                  obj = { ...target, parentId: plat.id }
                }
              })
            }
          }
        })
      }
    })
    return obj
  }

  const listDefault = ref<IGameRank[]>([])
  const list = computed(() => {
    return listDefault.value.map(e => {
      const gameData = getMap(e)
      return {
        ...e,
        ...gameData,
        nickname: maskUsername(e.nickname)
      }
    })
  })

  function formatData(data: {
    room_rank_list: IGameRank[]
  }) {
    listDefault.value = data.room_rank_list
  }

  function init() {
    const rankList = NetPacket.req_rank_with_player_list();
    PKwebsocket.instance.send(rankList, false, {
      callbackName: 'msg_notify_rank_with_player_list',
      callback: formatData
    })
  }

  function toDetail(item: any) {
    Local.set('selectedGameItem', item)
    router.push({ path: '/recentWin/detail' })
  }

  return {
    init,
    listDefault,
    toDetail,
    list
  }
}